#!/bin/bash
# 完整的 Node.js 环境配置脚本

set -e  # 遇到错误立即退出

echo "=========================================="
echo "  📦 完整安装 Node.js 环境"
echo "=========================================="
echo ""

# 1. 下载并安装 nvm
echo "步骤 1/4: 安装 nvm..."
echo ""

export NVM_DIR="$HOME/.nvm"

# 删除旧的空目录
if [ -d "$NVM_DIR" ] && [ ! -f "$NVM_DIR/nvm.sh" ]; then
    echo "   清理旧的 nvm 目录..."
    rm -rf "$NVM_DIR"
fi

if [ ! -f "$NVM_DIR/nvm.sh" ]; then
    echo "   📥 下载 nvm v0.39.0..."
    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
    
    if [ $? -ne 0 ]; then
        echo "❌ nvm 下载失败，尝试使用国内镜像..."
        curl -o- https://gitee.com/mirrors/nvm/raw/master/install.sh | bash
    fi
else
    echo "✅ nvm 已安装"
fi

echo ""
echo "步骤 2/4: 加载 nvm..."

# 加载 nvm
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

if ! command -v nvm &> /dev/null; then
    echo "❌ nvm 加载失败"
    exit 1
fi

echo "✅ nvm 已加载，版本: $(nvm --version)"

echo ""
echo "步骤 3/4: 安装 Node.js LTS..."

# 安装 Node.js
if ! command -v node &> /dev/null; then
    echo "   📥 下载并安装 Node.js LTS..."
    
    # 设置国内镜像加速
    export NVM_NODEJS_ORG_MIRROR=https://npmmirror.com/mirrors/node/
    
    nvm install --lts
    nvm use --lts
    nvm alias default lts/*
else
    echo "✅ Node.js 已安装"
fi

echo ""
echo "步骤 4/4: 配置 npm 镜像..."

# 配置 npm 使用国内镜像
if command -v npm &> /dev/null; then
    npm config set registry https://registry.npmmirror.com
    echo "✅ npm 镜像已设置为淘宝镜像"
fi

echo ""
echo "=========================================="
echo "  ✅ Node.js 环境配置完成！"
echo "=========================================="
echo ""
echo "📊 环境信息："
echo "   Node.js: $(node --version 2>/dev/null || echo '未找到')"
echo "   npm: $(npm --version 2>/dev/null || echo '未找到')"
echo "   nvm: $(nvm --version 2>/dev/null || echo '未找到')"
if command -v node &> /dev/null; then
    echo "   Node路径: $(which node)"
fi
echo ""

# 配置 shell 环境
echo "📝 配置 shell 环境..."

SHELL_CONFIG=""
if [ -f ~/.zshrc ]; then
    SHELL_CONFIG=~/.zshrc
elif [ -f ~/.bashrc ]; then
    SHELL_CONFIG=~/.bashrc
fi

if [ -n "$SHELL_CONFIG" ]; then
    if ! grep -q "NVM_DIR" "$SHELL_CONFIG"; then
        echo ""  >> "$SHELL_CONFIG"
        echo "# NVM 配置" >> "$SHELL_CONFIG"
        echo 'export NVM_DIR="$HOME/.nvm"' >> "$SHELL_CONFIG"
        echo '[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"' >> "$SHELL_CONFIG"
        echo '[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"' >> "$SHELL_CONFIG"
        echo "✅ 已添加 nvm 配置到 $SHELL_CONFIG"
    else
        echo "✅ shell 配置已存在"
    fi
fi

echo ""
echo "🎯 测试 Node.js 环境..."
if command -v node &> /dev/null && command -v npm &> /dev/null; then
    echo "✅ Node.js 和 npm 都可用！"
    echo ""
    echo "🚀 现在可以启动前端服务了："
    echo "   bash 一键启动前端.sh"
else
    echo "⚠️  需要重新加载 shell"
    echo "   请运行: source $SHELL_CONFIG"
    echo "   或者打开新终端窗口"
fi

echo ""
echo "=========================================="

